package cn.rwklyd.ecommerce.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.extra.mail.Mail;
import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import cn.rwklyd.ecommerce.pojo.Product;
import cn.rwklyd.ecommerce.pojo.Result;
import cn.rwklyd.ecommerce.pojo.Users;
import cn.rwklyd.ecommerce.service.ApiService;
import cn.rwklyd.ecommerce.until.JwtUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.zxing.WriterException;
import com.sun.mail.util.MailSSLSocketFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static cn.rwklyd.ecommerce.until.QRCodeUtil.generateQRCode;

/**
 * @author 键盘书生
 * @date 2024/12/1
 */
@RestController
@Slf4j
@RequestMapping("/api")
public class ApiController {
    @Autowired
    private ApiService apiService;  // 注入业务层
    @Autowired
    private JwtUtils jwtUtils;   // 注入jwt工具类
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;   // 注入Redis配置
    //用户或管理员登录
    @PostMapping("/login")
    public Result login(@RequestBody Users users){
        if (users.getUsername().isEmpty() || users.getPassword().isEmpty()) {
            return Result.error("用户名或密码为空");
        }
        log.info("用户登录：{}",users.getUsername());
        Users e = apiService.login(users);

        if (e == null) {
            return Result.error("用户名或密码错误");//登录失败，返回错误信息
        }
        //        登录成功,生成并下发令牌
        Map<String,Object> claims= new HashMap<>();
        claims.put("id",e.getId());
        claims.put("username",e.getUsername());
        claims.put("password",e.getPassword());
        String jwt = jwtUtils.generateJwt(claims);
        return Result.success(jwt);
    }

    //用户注册
    @PostMapping("/register")
    public Result register(@RequestBody Users users){
        if (users.getUsername().isEmpty() || users.getPassword().isEmpty() || users.getEmail().isEmpty()) {
            return Result.error("用户名或密码或邮箱为空");
        }
        // 从Redis中获取存储的验证码
        String storedCaptcha = (String) redisTemplate.opsForValue().get(users.getEmail());
        log.info("从Redis中获取的验证码: {}",storedCaptcha);
        log.info("用户输入的的验证码: {}",users.getCaptcha());
        if (storedCaptcha == null || !storedCaptcha.equals(users.getCaptcha())) {
            return Result.error("验证码错误");
        }

        if (apiService.register(users) == 1) {
            return Result.success("注册成功");
        } else {
            return Result.error("用户已存在");
        }
    }

    //用户注册邮箱验证
    @PostMapping("/emailVerification")
    public Result emailVerification(@RequestBody Users users) throws GeneralSecurityException {
        if (users.getEmail().isEmpty()) {
            return Result.error("邮箱为空");
        }
        String CaptchaCode = String.valueOf((int) ((Math.random() * 9 + 1) * 100000)); // 生成6位随机数
        // 保存验证码到 Redis，设置过期时间为5分钟
        redisTemplate.opsForValue().set(users.getEmail(), CaptchaCode, 5, TimeUnit.MINUTES);

        MailAccount mailAccount = new MailAccount();
        mailAccount.setHost("smtp.qq.com");
        mailAccount.setPort(465); // 使用 SSL/TLS 端口
        mailAccount.setAuth(true);
        mailAccount.setFrom("2458777387@qq.com");
        mailAccount.setUser("2458777387@qq.com");
        mailAccount.setPass("atzawunqctcidjfj");
        mailAccount.setSslEnable(true);

        // 设置 SSL 套接字工厂
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        mailAccount.setCustomProperty("mail.smtp.ssl.socketFactory", sf);

        String emailContent = "<!DOCTYPE html>" +
                "<html lang='en'>" +
                "<head>" +
                "    <meta charset='UTF-8'>" +
                "    <meta name='viewport' content='width=device-width, initial-scale=1.0'>" +
                "    <style>" +
                "        body { font-family: Arial, sans-serif; background-color: #f4f4f4; margin: 0; padding: 0; }" +
                "        .container { max-width: 600px; margin: 20px auto; background-color: #ffffff; padding: 20px; border-radius: 8px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); }" +
                "        .header { text-align: center; padding: 10px 0; }" +
                "        .header h1 { color: #007bff; }" +
                "        .content { padding: 20px; }" +
                "        .content p { font-size: 16px; line-height: 1.5; color: #333333; }" +
                "        .content h3 { color: #007bff; }" +
                "        .footer { text-align: center; padding: 10px 0; font-size: 12px; color: #777777; }" +
                "    </style>" +
                "</head>" +
                "<body>" +
                "    <div class='container'>" +
                "        <div class='header'>" +
                "            <h1>邮箱验证</h1>" +
                "        </div>" +
                "        <div class='content'>" +
                "            <p>您好，</p>" +
                "            <p>感谢您注册我们的服务。请使用以下验证码完成邮箱验证：</p>" +
                "            <h3>" + CaptchaCode + "</h3>" +
                "            <p>如果您没有请求此验证码，请忽略此邮件。(验证码5分钟后失效)</p>" +
                "        </div>" +
                "        <div class='footer'>" +
                "            <p>© 2024 校园学习使用. 保留所有权利。</p>" +
                "        </div>" +
                "    </div>" +
                "</body>" +
                "</html>";

        // 创建邮件并发送
        MailUtil.send(mailAccount, CollUtil.newArrayList(users.getEmail()), "邮箱验证", emailContent, true);

        return Result.success("验证码已发送");
    }

    // 获取商品列表
    @GetMapping("/getProductList")
    public Result getProductList(@RequestParam(defaultValue = "1") int page,
                                 @RequestParam(defaultValue = "8") int size) {
        PageHelper.startPage(page, size); // 使用 PageHelper 进行分页
        List<Product> productList = apiService.getProductList();
        PageInfo<Product> pageInfo = new PageInfo<>(productList);
        return Result.success(pageInfo);
    }

    //生成支付链接
    @GetMapping("/generatePaymentLink")
    public Result generatePaymentLink(@RequestParam String id, @RequestParam Double amount) throws IOException, WriterException {
        // 请求路径
        String baseUrl = "http://javaweb.rwklyd.icu:8082/QRcode/rechargeQRCode";
        // 拼接请求参数
        String urlWithParams = String.format("%s?id=%s&amount=%s", baseUrl, id, amount);
        log.info("拼接后的URL: {}", urlWithParams);
        // 生成二维码
        String qrCodeBase64 = generateQRCode(urlWithParams);
        return Result.success("未出库", qrCodeBase64); // 返回二维码的Base64字符串

    }

    //轮询用户余额
    @GetMapping("/pollingBalance")
    public Result pollingBalance(@RequestParam String id) {
        Double Balance = apiService.pollingBalance(id);
        return Result.success(Balance);
    }

    //搜索商品信息
    @GetMapping("/search")
    public Result search(@RequestParam String key){
        List<Product> products = apiService.search(key);
        return Result.success(products);
    }



}
